package com.itheima.blog.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.api.client.UserClient;
import com.itheima.api.client.dto.WebUser;
import com.itheima.blog.util.UserThreadLocalUtils;
import com.itheima.blog.web.domain.po.TBlog;
import com.itheima.blog.web.domain.po.TComment;
import com.itheima.blog.web.mapper.TBlogMapper;
import com.itheima.blog.web.mapper.TCommentMapper;
import com.itheima.blog.web.service.ITCommentService;
import com.itheima.common.domain.PageResDto;
import com.itheima.common.domain.R;
import com.itheima.common.utils.CollUtils;
import com.itheima.common.vo.CommentPageDTO;
import com.itheima.common.vo.CommentVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.itheima.blog.web.domain.po.TComment;
import com.itheima.blog.web.mapper.TCommentMapper;
import com.itheima.blog.web.service.ITCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author sj
 * @since 2023-07-11
 */
@Service
@RequiredArgsConstructor
public class TCommentServiceImpl extends ServiceImpl<TCommentMapper, TComment> implements ITCommentService {

    private final UserClient userClient;
    private final TBlogMapper blogMapper;

    @Override
    public PageResDto<CommentVO> commentPage(CommentPageDTO dto) {
        //处理查询条件
        String name = dto.getName();
        List<Integer> userIds = null;
        if (StringUtils.isNotBlank(name)) {
            //根据用户昵称查询用户
            userIds = userClient.queryWebUsersByName(name);
        }

        //构建分页条件
        Page<TComment> page = lambdaQuery()
                .eq(CollUtils.isNotEmpty(userIds), TComment::getUserId, userIds)
                .like(StringUtils.isNotBlank(dto.getContent()), TComment::getContent, dto.getContent())
                .page(PageDTO.of(dto.getPage(), dto.getSize()));
        //处理结果
        List<TComment> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return new PageResDto<CommentVO>(dto, page.getTotal(), null);
        }
        //评论集合
        List<TComment> comments = records.stream().filter(c -> {
            return StringUtils.isNotBlank(c.getTargetCommentId());
        }).collect(Collectors.toList());
        //回复集合
        List<TComment> replies = records.stream().filter(c -> {
            return StringUtils.isBlank(c.getTargetCommentId());
        }).collect(Collectors.toList());
        //返回集合
        List<CommentVO> vos = new ArrayList<>();

        //封装用户信息map
        List<String> userIdList = records.stream().map(TComment::getUserId).collect(Collectors.toList());
        List<Integer> list = userIdList.stream().map(Integer::valueOf).collect(Collectors.toList());
        List<WebUser> userList = userClient.queryWebUsersByIds(list);
        Map<Integer, WebUser> userMap = userList.stream().collect(Collectors.toMap(WebUser::getId, c -> c));
        //判断查询的是评论还是回复
        Integer type = dto.getType();
        if (type == 1) {
            //查询评论
            vos = comments.stream().map(c -> {
                WebUser user = userMap.get(Integer.valueOf(c.getUserId()));
                return CommentVO.builder()
                        .id(c.getId())
                        .commentName(user.getNickname())
                        .content(c.getContent())
                        .createTime(c.getCreateTime())
                        .image(user.getImage())
                        .type(type)
                        .build();
            }).collect(Collectors.toList());
        } else {
            //todo 多封装一下回复人昵称
        }

        return new PageResDto<CommentVO>(dto, page.getTotal(), vos);
    }

    @Override
    @Transactional
    public R<String> delete(List<Integer> ids) {
        //先删除评论对应所有下级回复
        LambdaQueryWrapper<TComment> wrapper = new LambdaQueryWrapper<TComment>().eq(TComment::getTargetCommentId, ids)
                .eq(TComment::getCommentId, ids);
        boolean remove = remove(wrapper);

        //删除对应评论
        boolean b = removeBatchByIds(ids);

        return R.ok(null);
    }

    @Override
    public List getMyCommentList() {
        return lambdaQuery().eq(TComment::getUserId, UserThreadLocalUtils.getWebUserId()).list();
    }

    @Override
    public List getMyReply() {
        List<Long> blogIds = blogMapper.
                selectList(new LambdaQueryWrapper<TBlog>().eq(TBlog::getUserId, UserThreadLocalUtils.getWebUserId()))
                .stream().map(TBlog::getId).collect(Collectors.toList());

        List<TComment> list1 = lambdaQuery()
                .eq(TComment::getTargetUserId, UserThreadLocalUtils.getWebUserId()).list();

        List<TComment> list2 = null;
        if (blogIds!=null && blogIds.size()>0) {
            list2 = lambdaQuery()
                    .in(TComment::getBlogId, blogIds)
                    .list();
            return Stream.concat(list1.stream(), list2.stream()).collect(Collectors.toList());
        }
        return list1;
    }
}
